﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace mesoBoard.Data.Repositories
{
    public class MessageRepository : IMessageRepository
    {
        private mbEntities db;

        public MessageRepository(mbEntities mbDataContext)
        {
            this.db = mbDataContext;
        }

        public void SendMessage(Message TheMessage)
        {
            db.Messages.AddObject(TheMessage);
            db.SaveChanges();
        }

        public void SetIsRead(Message TheMessage)
        {
            TheMessage.IsRead = true;
            db.SaveChanges();
        }

        public Message GetMessage(int MessageID)
        {
            return db.Messages.FirstOrDefault(x => x.MessageID == MessageID);
        }

        public IEnumerable<Message> GetNewMessages(int UserID)
        {
            return GetAllMessagesByUser(UserID).Where(x => x.ToUserID == UserID && x.IsRead == false).OrderByDescending(x => x.DateSent);
        }

        public IEnumerable<Message> GetAllMessagesByUser(User TheUser)
        {
            return db.Messages.Where(x => x.FromUserID == TheUser.UserID || x.ToUserID == TheUser.UserID).OrderByDescending(x => x.DateSent);
        }

        public IEnumerable<Message> GetAllMessagesByUser(int UserID)
        {
            return db.Messages.Where(x => x.FromUserID == UserID || x.ToUserID == UserID).OrderByDescending(x => x.DateSent);
        }

        public void DeleteMessage(int MessageID)
        {
            Message TheMessage = GetMessage(MessageID);
            db.Messages.DeleteObject(TheMessage);
            db.SaveChanges();
        }
    }
}
